$(function () {
    $("#jqGrid").jqGrid({
        url: baseURL + 'water/tdataerr2021/list',
        postData:{'dataMonth':vm.q.dataMonth},
        datatype: "json",
        colModel: [
            { label: 'rowId', name: 'rowId', index: 'row_id', width: 90, key: true,hidden:true },
			{ label: '年月', name: 'dataMonth', index: 'data_month', width: 90 },
			{ label: '城市', name: 'cityName', index: 'city_name', width: 50,hidden:true },
			{ label: '区域', name: 'areaName', index: 'area_name', width: 80 },
			{ label: '分所', name: 'unitName', index: 'unit_name', width: 80 },
            { label: '小区', name: 'proName', index: 'pro_name', width: 150 },
			{ label: '小区数', name: 'proCount', index: 'pro_count', width: 80,
                formatter:function(cellvalue, options, rowObject){
                    if(!cellvalue){
                        return ''
                    }
                    else{
                        return cellvalue
                    }
                }
            },
			{ label: '故障小区', name: 'proErr', index: 'pro_err', width: 80,
                formatter:function(cellvalue, options, rowObject){
                    if(!cellvalue){
                        return ''
                    }
                    else{
                        return cellvalue
                    }
                }},
            { label: '小区故障率', name: 'ratePro', index: 'rate_pro', width: 80 ,hidden:true,
                formatter:function(cellvalue, options, rowObject){
                    if(!cellvalue){
                        return '';
                    }
                    else{
                        return cellvalue+'%';
                    }
                }},
            { label: '设备数', name: 'deviceCount', index: 'device_count', width: 80 },
			{ label: '故障设备', name: 'deviceErr', index: 'device_err', width: 80,
                formatter:function(cellvalue, options, rowObject){
                    if(!cellvalue){
                        return '0';
                    }
                    else{
                        return cellvalue;
                    }
                }},
            { label: '设备故障率', name: 'rateErr', index: 'rate_err', width: 80,
                formatter:function(cellvalue, options, rowObject){
                    if(!cellvalue){
                        return '0';
                    }
                    else{
                        return cellvalue+'%';
                    }
                }
            },
            { label: '板数', name: 'boardCount', index: 'board_count', width: 80 },
            { label: '故障板数', name: 'boardErr', index: 'board_err', width: 80 },
            { label: '板故障率', name: 'boardRate', index: 'board_rate', width: 80,
                formatter:function(cellvalue, options, rowObject){
                    if(!cellvalue){
                        return '0';
                    }
                    else{
                        return cellvalue+'%';
                    }
                } },
            { label: '更新时间', name: 'updateTime', index: 'update_time', width: 80 },
            { label: '维护人', name: 'debugerName', index: 'debuger_name', width: 80 },
            { label: '超期数', name: 'overCount', index: 'over_count', width: 80,
                formatter:function(cellvalue, options, rowObject){
                    if(!cellvalue){
                        return '';
                    }
                    else{
                        var rst = cellvalue,value=cellvalue;
                        switch(value){
                            case 1:
                                rst = '<span class="label label-danger">超期</span>';
                                break;
                        }
                        return rst;
                    }
                }
            }
        ],
		viewrecords: true,
        height: $(window).height()-130,
        rowNum: 100,
		rowList : [10,30,50],
        rownumbers: true, 
        rownumWidth: 25, 
        autowidth:true,
        multiselect: true,
        sortorder: "asc",
        sortname:"data_month desc,city_name asc, area_name asc, unit_name asc,pro_name",
        pager: "#jqGridPager",
        jsonReader : {
            root: "page.list",
            page: "page.currPage",
            total: "page.totalPage",
            records: "page.totalCount"
        },
        prmNames : {
            page:"page", 
            rows:"limit", 
            order: "order"
        },
        onSelectRow: function () {
            //SelectRowIndx = GetJqGridRowIndx("#" + this.id);
        },
        gridComplete:function(){
        	//隐藏grid底部滚动条
        	//$("#jqGrid").closest(".ui-jqgrid-bdiv").css({ "overflow-x" : "hidden" });

            var ids = $("#jqGrid").getDataIDs();
            for (var i = 0; i < ids.length; i++) {
                var rowData = $("#jqGrid").getRowData(ids[i]);
                //console.log(rowData.proName);
                if (rowData.proName.indexOf('PRO')>-1) {
                    $("#jqGrid").find('#' + ids[i]).find("td").addClass("totalRowColor");
                }

                if (rowData.rateErr.indexOf('%')>-1 && rowData.proName.indexOf('PRO') == -1) {
                    var rateErr = rowData.rateErr.replace("%","")*1.0;
                    if (rateErr >= 1.0 && rateErr < 10){
                        $("#jqGrid").find('#' + ids[i]).find("td").addClass("errRow_1-10");
                    }
                    else if(rateErr >= 10.0 && rateErr <30.0)
                    {
                        $("#jqGrid").find('#' + ids[i]).find("td").addClass("errRow_10-30");
                    }
                    else if(rateErr >= 30.0 && rateErr <60.0)
                    {
                        $("#jqGrid").find('#' + ids[i]).find("td").addClass("errRow_30-60");
                    }
                    else if(rateErr >= 60.0)
                    {
                        $("#jqGrid").find('#' + ids[i]).find("td").addClass("errRow_60");
                    }
                }
            }

            //$("#" + this.id).jqGrid('setSelection', SelectRowIndx);
        }
    });

    $(function () {
        $('#inputClear').click(function () {
            $('input')[0].value = "";
            vm.q.value="";
        })
    });


    $(function () {
        var today=new Date(new Date()-24*60*60*1000);//定义日期对象
        var yyyy = today.getFullYear();//通过日期对象的getFullYear()方法返回年
        var MM = today.getMonth()+1;//通过日期对象的getMonth()方法返回年
        var dd = today.getDate();//通过日期对象的getDate()方法返回年

        $("#datetime1").datetimepicker({
            format: 'YYYY-MM',
            locale: moment.locale('zh-cn')
        });

        $("#datetime1").val(yyyy+"-"+MM);

        $('#inputClear1').click(function () {
            $('#datetime1')[0].value = "";
            vm.q.dataMonth="";
        });
    });
});



function zTreeOnDblClick(event, treeId, treeNode) {
    vm.q.dept = treeNode.deptId;
    vm.newpage = true;

    var temp='';
    var node = treeNode;
    while (node) {
        var x = node.name.split('|');
        if (x.length >= 2){
            temp = x[1]+'_'+temp;
        }else if (x.length >=1){
            temp = x[0]+'_'+temp;
        }
        node = node.getParentNode();
    }
    vm.q.dept = temp.substring(0,temp.length-1);

    vm.reload();

    //alert(treeNode.deptId);
    //alert(treeNode ? treeNode.tId + ", " + treeNode.name : "isRoot");
};

var settingLeft = {
    data: {
        simpleData: {
            enable: true,
            idKey: "deptId",
            pIdKey: "parentId",
            rootPId: -1
        },
        key: {
            url:"nourl"
        }
    },
    callback: {
        onDblClick: zTreeOnDblClick
    }
};

var ztree;

var vm = new Vue({
	el:'#rrapp',
	data:{
		showList: true,
		title: null,
		tDataErr2021: {},
        newpage : false,
        searchKeyDictInfo: {},
        q:{
            key:'',
            value:'',//(new Date()).getFullYear()+'-'+(((new Date()).getMonth()+1)>9 ? ((new Date()).getMonth()+1):'0'+((new Date()).getMonth()+1)),
            dept:null,
            dataMonth:(new Date()).getFullYear()+'-'+(((new Date()).getMonth()+1)>9 ? ((new Date()).getMonth()+1):'0'+((new Date()).getMonth()+1)),
        }
	},
	methods: {
        getSearchKeyDict: function(){
            $.get(baseURL + "sys/dict/list",{name:"qkey_tdataerr2021"}, function(r){
                vm.searchKeyDictInfo = r.page.list;
            });
        },
        query: function () {
            if(vm.q.value != null && vm.q.value != ""
                && (vm.q.key == null || vm.q.key == "")){
                alert('请选择查询条件!');
                return;
            }

            vm.q.dataMonth = $("#datetime1").val();

            vm.newpage=true;
			vm.reload();
		},
		add: function(){
			vm.showList = false;
			vm.title = "新增";
			vm.tDataErr2021 = {};
		},
		update: function (event) {
			var dataMonth = getSelectedRow();
			if(dataMonth == null){
				return ;
			}
			vm.showList = false;
            vm.title = "修改";
            
            vm.getInfo(dataMonth)
		},
		saveOrUpdate: function (event) {
		    $('#btnSaveOrUpdate').button('loading').delay(1000).queue(function() {
                var url = vm.tDataErr2021.dataMonth == null ? "water/tdataerr2021/save" : "water/tdataerr2021/update";
                $.ajax({
                    type: "POST",
                    url: baseURL + url,
                    contentType: "application/json",
                    data: JSON.stringify(vm.tDataErr2021),
                    success: function(r){
                        if(r.code === 0){
                             layer.msg("操作成功", {icon: 1});
                             vm.reload();
                             $('#btnSaveOrUpdate').button('reset');
                             $('#btnSaveOrUpdate').dequeue();
                        }else{
                            layer.alert(r.msg);
                            $('#btnSaveOrUpdate').button('reset');
                            $('#btnSaveOrUpdate').dequeue();
                        }
                    }
                });
			});
		},
		del: function (event) {
			var dataMonths = getSelectedRows();
			if(dataMonths == null){
				return ;
			}
			var lock = false;
            layer.confirm('确定要删除选中的记录？', {
                btn: ['确定','取消'] //按钮
            }, function(){
               if(!lock) {
                    lock = true;
		            $.ajax({
                        type: "POST",
                        url: baseURL + "water/tdataerr2021/delete",
                        contentType: "application/json",
                        data: JSON.stringify(dataMonths),
                        success: function(r){
                            if(r.code == 0){
                                layer.msg("操作成功", {icon: 1});
                                $("#jqGrid").trigger("reloadGrid");
                            }else{
                                layer.alert(r.msg);
                            }
                        }
				    });
			    }
             }, function(){
             });
		},
		getInfo: function(dataMonth){
			$.get(baseURL + "water/tdataerr2021/info/"+dataMonth, function(r){
                vm.tDataErr2021 = r.tDataErr2021;
            });
		},
        getDeptTreeLeft: function(){
            $.get(baseURL + "water/waterdept/queryDeptAll", function(r){
                //console.log(r);
                ztree = $.fn.zTree.init($("#deptTreeLeft"), settingLeft, r);
                var node = ztree.getNodeByParam("deptId", vm.q.dept);
                if(node != null){
                    ztree.selectNode(node);
                    vm.q.dept = node.deptId;
                }
            })
        },
        outxls: function(){
            var total = $("#jqGrid").jqGrid('getGridParam', 'records') + "";
            var dept = vm.q.dept==null ? "" : vm.q.dept+  "";
            var url = baseURL
                + "water/tdataerr2021/export?params="
                + encodeURIComponent(JSON.stringify({dataMonth:vm.q.dataMonth,key:vm.q.key,value:vm.q.value,dept:dept,limit:total,page:"1"}));

            //console.log(decodeURIComponent(url));
            location.href = url;
        },
		reload: function (event) {
			vm.showList = true;
			var page = $("#jqGrid").jqGrid('getGridParam','page');
            if(vm.newpage){page = "1";}
            $("#jqGrid").jqGrid('setGridParam',{
                postData:{'key': vm.q.key,'value':vm.q.value,'dept':vm.q.dept,'dataMonth':vm.q.dataMonth},
                page:page
            }).trigger("reloadGrid");
        }
    },
    created: function (){
        this.getDeptTreeLeft();
        this.getSearchKeyDict();
    }
});